﻿using System;
using System.Collections.Generic;
using System.Linq;
using _5E.Infrastructure.Domain;
using WholesaleOnline.Model.BusinessRules;

namespace WholesaleOnline.Model
{
    partial class WoBasket : EntityBase<Guid>, IAggregateRoot
    {
        private IList<WoBasketItem> m_Items = new List<WoBasketItem>();
        public virtual IList<WoBasketItem> Items
        {
            get { return m_Items; }
            set { m_Items = value; }
        }

        private WoSeller m_Seller = null;
        public virtual WoSeller Seller
        {
            get { return m_Seller; }
            set { m_Seller = value; }
        }

        public virtual decimal TotalPrice
        {
            get { return Items.Sum(i => i.TotalPrice); }
        }

        public WoBasket()
        {
            Id = Guid.NewGuid();
        }

        public WoBasket(Guid buyerId, Guid sellerId)
            : this()
        {
            BuyerId = buyerId;
            SellerId = sellerId;
        }

        public virtual void Add(WoProduct product, Int32 qty)
        {
            if (ContainsItemFor(product))
                GetItemFor(product).IncreaseItemQtyBy(qty);
            else
                Items.Add(BasketItemFactory.CreateItemFor(product, qty, this));
        }

        private bool ContainsItemFor(WoProduct product)
        {
            return Items.Any(i => i.Contains(product));
        }

        private WoBasketItem GetItemFor(WoProduct product)
        {
            return Items.Where(i => i.Contains(product)).First();
        }

        public virtual void Remove(WoProduct product)
        {
            if (ContainsItemFor(product))
                Items.Remove(GetItemFor(product));
        }

        public virtual void ChangeQtyBy(WoProduct product, Int32 qty)
        {
            if (ContainsItemFor(product))
                GetItemFor(product).ChangetItemQtyTo(qty);
        }

        protected override void Validate()
        {
            foreach (WoBasketItem item in Items)
            {
                if (0 < item.BrokenRules.Count())
                    base.AddBrokenRule(BasketBusinessRules.ItemInvalid);
            }
        }
    }
}
